package com.eureka.baseconfig.Intercept;

import com.eureka.baseconfig.annotation.Auth;
import com.eureka.bclass.base.BaseException;
import com.eureka.bclass.base.BaseLoginUserInfo;
import com.eureka.bclass.enums.SysKeyEnum;
import com.eureka.bclass.enums.SysStateEnum;
import com.eureka.bclass.util.StrUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description Token拦截器，需要在WebMvcConfig中配置
 * @Author lixing
 * @Date 2021/6/9 13:56
 */
@Component
public class AuthIntercept implements HandlerInterceptor {
    /**
     * @Description 前置拦截
     * @Author lixing
     * @Date 2021/6/9 13:58
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取注解对象
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Auth auth = handlerMethod.getMethodAnnotation(Auth.class);
        if (null != auth ) {
            // 获取注解中的参数
            boolean isCheck = auth.isCheck();
            if (isCheck) {
                // System.out.println(JSONObject.toJSONString(request.getHeaderNames()));
                String userAccount = request.getHeader(SysKeyEnum.USERINFO_ACCOUNT.getKey());
                String userPhone = request.getHeader(SysKeyEnum.USERINFO_PHONE.getKey());
                if (!StrUtil.isEffective(userAccount)) {
                    throw new BaseException(SysStateEnum.RESPONSE_STATUS_FALSE_TOKEN_TIMEOUT.getValue(), SysStateEnum.RESPONSE_STATUS_FALSE_TOKEN_TIMEOUT.getDescribe());
                }
                //
                BaseLoginUserInfo baseLoginUserInfo = new BaseLoginUserInfo();
                baseLoginUserInfo.setAccount(userAccount);
                baseLoginUserInfo.setPhone(userPhone);
                request.setAttribute(SysKeyEnum.USERINFO.getKey(), baseLoginUserInfo);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
